package com.zhuyi.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import com.zhuyi.common.config.ZhuYiConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class Sm2Utils {
    public static String encrypt(String plainText) {
        SM2 sm2 = SmUtil.sm2(ZhuYiConfig.getPrivateKey(), ZhuYiConfig.getPublicKey());
        // 公钥加密，私钥解密
        String encryptStr = sm2.encryptBcd(plainText, KeyType.PublicKey);
        return encryptStr;
    }

    // SM2非对称解密
    public static String decrypt(String encryptStr) throws Exception {
        SM2 sm2 = SmUtil.sm2(ZhuYiConfig.getPrivateKey(), ZhuYiConfig.getPublicKey());
        String decryptStr = null;
        try {
            decryptStr = StrUtil.utf8Str(sm2.decryptFromBcd(encryptStr, KeyType.PrivateKey));
        }catch (Exception ex) {
            throw new Exception("密码解密错误");
        }
        return decryptStr;
    }
}